package cn.jzk.mySpringSecurity_noSeparation.SecurityHandler;

import cn.jzk.mySpringSecurity_noSeparation.Common.Enums.AppHttpCodeEnum;
import cn.jzk.mySpringSecurity_noSeparation.Common.Result.ResponseResult;
import cn.jzk.mySpringSecurity_noSeparation.Common.Utils.MyJsonUtils;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * 【会话并发】响应处理器（通俗点讲就是挤号）
 * @author jiangzk
 */
public class MySessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException{

        HttpServletResponse response = event.getResponse();

        // 设置响应的内容类型和字符集
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        // 返回自定义的 JSON 响应信息
        try (PrintWriter writer = response.getWriter()) {
            writer.print(MyJsonUtils.stringify(
                    ResponseResult.errorResult(AppHttpCodeEnum.LOGGED_IN_ELSEWHERE.getCode(),
                            AppHttpCodeEnum.LOGGED_IN_ELSEWHERE.getMsg())));
        }
    }
}
